<script setup>
import { computed, markRaw, nextTick, onBeforeMount, ref } from 'vue'
import { getResourceListApi, removeResourceByIdApi } from '../../apis/resource'
import { ElMessage } from 'element-plus'
import { api as viewerApi } from 'v-viewer'
import { genFileId } from 'element-plus'
import { openMessageBox } from '../../utils/MessageBox/index.js'
import { Delete, InfoFilled } from '@element-plus/icons-vue'
import { getElementByImgApi, getTagByImgApi, saveTagAndElement } from '../../apis/image'
import _ from 'lodash'

//资源列表
const resourceList = ref([])
const previewImageUrlList = computed(() => {
  return resourceList.value.map((item) => item.resourceValue)
})
const uploadRef = ref(null)
const resourceLabel = ref('')
// const randomTagColor=ref(['#FF6666','#FFB466','#FFFF66','#66FF66','#66FFFF','#66B4FF','#6666FF','#B466FF','#FF66FF','#FF66B4'])
const randomTagColor = ref(['#36BCCB', '#DB6BCF', '#2498D1', '#BBBDE6', '#4045B2', '#A0DC2C', '#007E99', '#FFA8A8', '#2391FF', '#FFC328'])
//允许上传的文件类型
// const whiteList = ['image/jpeg', 'image/png', 'image/jpg']
const whiteList = []

//编辑模式
const isEditMode = ref(false)

/**
 * 判断上传文件的大小和格式
 * @param rawFile
 * @returns {boolean}
 */
const dialogTableVisible = ref(false)

/**
 * 上传文件列表
 * @type {Ref<UnwrapRef<*[]>>}
 */
const uploadFileList = ref([])
const beforeAvatarUpload = async (rawFile) => {

  resourceLabel.value = await openMessageBox('请输入图片标题',
      (value) => value !== null, markRaw(Delete),
      `确定`,
      '用户取消输入'
  )

  // resourceLabel.value = await openMessageBox(
  //   "请输入文件标签",
  //   (value) => value !== null,
  //   markRaw(Delete),
  //   `确定`,
  //   "Input canceled"
  // );
  // resourceLabel.value = 'img'
  // console.log('a' + resourceLabel.value)

  // if (!whiteList.includes(rawFile.type)) {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片不能大于10MB!')
    return false
  }
  return true
}

//重新发送请求获取数据的方法
const initResourceList = async () => {
  resourceList.value = (await getResourceListApi()).data
}

/**
 * 组件挂载之前先获取数据
 */
onBeforeMount(() => {
  initResourceList()
})

/**
 * 删除资源数据,删除之后重新获取数据
 * @param id
 * @returns {Promise<void>}
 */
const handleDelete = async (id) => {
  await removeResourceByIdApi(id)
  await initResourceList()
}

/**
 * 上传成功的回调
 * @returns {Promise<void>}
 */
const resourceId = ref('')
const resourceValue=ref('')
async function openDialogAndGetTag (resource_value, resource_id) {
  resourceValue.value=resource_value
  resourceId.value = resource_id
  let tagsString = (
      await getTagByImgApi({
        imgUrl: resource_value,
        resource_id,
      })
  ).data

  let elementsString = (
      await getElementByImgApi({
        imgUrl: resource_value,
        resource_id,
      })
  ).data
  // ElMessage.success('上传成功')
  generatedTags.value = tagsString.split('。')
  if(typeof generatedTags.value==='string'){
    generatedTags.value = tagsString.split('。')
  }
  generatedElements.value = elementsString.split('。')
  if(typeof generatedElements.value==='string'){
    generatedElements.value = elementsString.split('。')
  }
  console.log('tag',generatedTags.value,tagsString)
  console.log('element',generatedElements.value,elementsString)
  dialogTableVisible.value = true
}


const handleUploadSuccess = async (response, file, fileList) => {
  console.log(response)
  resourceId.value = response.data.id
  resourceValue.value=response.data.resourceValue
  if (response.status === true) {
    await openDialogAndGetTag(response.data.resourceValue, response.data.id)

    resourceList.value = (await getResourceListApi()).data
  }
}

const handleExceed = (files) => {
  uploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  uploadRef.value.handleStart(file)
}

const handlePreview = (index) => {
  viewerApi({
    options: {
      toolbar: true,
      initialViewIndex: index,
    },
    images: previewImageUrlList.value,
  })
}

const handleEditResource = (row) => {
  console.log('row', row)
}

const handleChange = (uploadFile, uploadFiles) => {

}

/**
 * 用户选择保存的标签
 * @type {Ref<UnwrapRef<*[]>>}
 */
const saveTagList = ref([])
const generatedTags = ref([])
const addTag = (item) => {
  if (!saveTagList.value.includes(item)) {
    saveTagList.value.push(item)
  } else {
    ElMessage.error('您已经选择该标签')
  }
}
const removeTag = (tag) => {
  saveTagList.value = saveTagList.value.filter(item => item !== tag)
  checkAllTagValue.value = false
}
const checkAllTagValue = ref(true)
const onCheckAllTagChange = () => {
  if (checkAllTagValue.value) {
    saveTagList.value = generatedTags.value
    revertCheckTagValue.value = false
  } else {
    saveTagList.value = []
  }

}
const revertCheckTagValue = ref(false)
const onRevertCheckTagChange = () => {
  checkAllTagValue.value = false
  saveTagList.value = generatedTags.value.filter(item => !saveTagList.value.includes(item))
}

/**
 * 用户选择保存的元素
 * @type {Ref<UnwrapRef<*[]>>}
 */
const saveElementList = ref([])
const generatedElements = ref([])
const addElement = (item) => {
  if (!saveElementList.value.includes(item)) {
    saveElementList.value.push(item)
  } else {
    ElMessage.error('您已经选择该元素')
  }
}
const removeElement = (element) => {
  saveElementList.value = saveElementList.value.filter(item => item !== element)
  checkAllElementValue.value = false
}
const checkAllElementValue = ref(true)
const onCheckAllElementChange = () => {
  if (checkAllElementValue.value) {
    saveElementList.value = generatedElements.value
    revertCheckElementValue.value = false
  } else {
    saveElementList.value = []
  }
  console.log('save',saveElementList.value)

}
const revertCheckElementValue = ref(false)
const onRevertCheckElementChange = () => {
  checkAllElementValue.value = false
  saveElementList.value = generatedElements.value.filter(item => !saveElementList.value.includes(item))
}

/**
 * 对话框显示时触发的事件
 */
const handleOnDialogOpen = () => {
  if (checkAllTagValue.value) {
    saveTagList.value = generatedTags.value
  } else {
    saveTagList.value = []
  }
  if (checkAllElementValue.value) {
    saveElementList.value = generatedElements.value
  } else {
    saveElementList.value = []
  }

}

const handleOnDialogClose = async () => {
  resourceList.value = (await getResourceListApi()).data

  generatedTags.value = []
  checkAllTagValue.value = true
  revertCheckTagValue.value = false
  saveTagList.value = []
  dialogTableVisible.value = false
}

const tagIntosql = async (saveTagList,saveElementList) => {

  await saveTagAndElement({
    tags: saveTagList.join(','),
    elements:saveElementList.join(','),
    resource_id: resourceId.value,
    resource_value:resourceValue.value,
  })



  dialogTableVisible.value = false

}
const newTagInputRef=ref(null)
const newTagInputVisible=ref(false)
const newTag=ref('')
const handleNewTagInputConfirm=()=>{
  if (newTag.value) {
    saveTagList.value.push(newTag.value)
  }
  newTagInputVisible.value = false
  newTag.value = ''
}
const showNewTagInput=()=>{
  newTagInputVisible.value = true
  nextTick(() => {
    newTagInputRef.value.input.focus()
  })
}

const newElementInputRef=ref(null)
const newElementInputVisible=ref(false)
const newElement=ref('')
const handleNewElementInputConfirm=()=>{
  if (newElement.value) {
    saveElementList.value.push(newElement.value)
  }
  newElementInputVisible.value = false
  newElement.value = ''
}
const showNewElementInput=()=>{
  newElementInputVisible.value = true
  nextTick(() => {
    newElementInputRef.value.input.focus()
  })
}
</script>

<template>
  <el-dialog
      class="dialog"
      @open="handleOnDialogOpen"
      @close="handleOnDialogClose"
      v-model="dialogTableVisible"
      title="请选择您需要的标签"
      width="900"
  >

    <div class="dialog-header">
      <h4>请选择标签</h4>
      <el-checkbox v-model="checkAllTagValue"
                   @change="onCheckAllTagChange">全选
      </el-checkbox>
      <el-checkbox v-model="revertCheckTagValue"
                   @change="onRevertCheckTagChange">反选
      </el-checkbox>
    </div>
    <div class="tag-list">
      <el-tag type="primary"
              :style="{color:'black',}"
              :color="randomTagColor[_.random(0,randomTagColor.length-1)]"
              v-for="tag in generatedTags"
              @click="addTag(tag)">{{ tag }}
      </el-tag>
    </div>
    已选择
    <div class="tag-list">
      <el-tag type="danger"
              closable
              :style="{color:'black',}"
              @close="removeTag(item)"
              :color="randomTagColor[index]"
              v-for="(item,index) in saveTagList">{{ item }}
      </el-tag>
      <el-input
          v-if="newTagInputVisible"
          ref="newTagInputRef"
          v-model="newTag"
          class="ml-1 w-20"
          size="small"
          @keyup.enter="handleNewTagInputConfirm"
          @blur="handleNewTagInputConfirm"
      />
      <el-button v-else class="button-new-tag ml-1" size="small" @click="showNewTagInput">
        + 添加新标签
      </el-button>
    </div>

    <div class="dialog-header">
      <h4>请选择元素</h4>
      <el-checkbox v-model="checkAllElementValue"
                   @change="onCheckAllElementChange">全选
      </el-checkbox>
      <el-checkbox v-model="revertCheckElementValue"
                   @change="onRevertCheckElementChange">反选
      </el-checkbox>
    </div>

    <div class="tag-list">
      <el-tag type="primary"
              :style="{color:'black',}"
              v-for="(element,index) in generatedElements"
              :color="randomTagColor[index]"
              @click="addElement(element)">{{ element }}
      </el-tag>
    </div>
    已选择
    <div class="tag-list">
      <el-tag type="danger"
              closable
              :style="{color:'black',}"
              :color="randomTagColor[index]"
              @close="removeElement(item)"
              v-for="(item,index) in saveElementList">{{ item }}
      </el-tag>
      <el-input
          v-if="newElementInputVisible"
          ref="newElementInputRef"
          v-model="newElement"
          class="ml-1 w-20"
          size="small"
          @keyup.enter="handleNewElementInputConfirm"
          @blur="handleNewElementInputConfirm"
      />
      <el-button v-else class="button-new-tag ml-1" size="small" @click="showNewElementInput">
        + 添加新元素
      </el-button>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button type="primary"
                   @click="tagIntosql(saveTagList,saveElementList)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <div class="header">


  <el-button type="primary"
             v-if="!isEditMode"
             @click="isEditMode=!isEditMode"
  >编辑
  </el-button>
  <el-button type="primary"
             v-else
             @click="isEditMode=!isEditMode"
  >保存
  </el-button>
  <el-upload
      ref="uploadRef"
      :auto-upload="true"
      class="upload"
      v-model:file-list="uploadFileList"
      :data="{ resourceLabel, userType: 0 }"
      :action="`/api/qiniu/upload/${resourceLabel}/2`"
      :on-success="handleUploadSuccess"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :before-upload="beforeAvatarUpload"
  >


    <!--<template #trigger>-->
    <!--  <el-button type="primary">添加文件</el-button>-->
    <!--</template>-->
    <el-tooltip
        class="box-item"
        effect="dark"
        content="目前只支持图片文件"
        placement="top"
    >
      <el-button type="primary">上传文件</el-button>
    </el-tooltip>

    <!--<template #tip>-->
    <!--  <div class="el-upload__tip">图片不能大于1MB!</div>-->
    <!--</template>-->
  </el-upload>
  </div>
  <el-table class="table" :data="resourceList">
    <el-table-column type="index"
                     label="序号"></el-table-column>

    <el-table-column prop="resourceLabel"
                     label="标题"
                     width="100">
      <template v-slot="{ row }">
        <el-input v-show="isEditMode"
                  v-model="row.resourceLabel"
                  placeholder="请输入标签名"></el-input>
        <div v-show="!isEditMode">
          {{ row.resourceLabel }}
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="resourceTag"
                     label="标签">
      <template v-slot="{ row }">
        <div v-if="row.resourceTag===null||row.resourceTag.split(',').length===1">
          暂无数据
        </div>
        <div v-else
             id="tag-container">
          <el-tag type="success"
                  :closable="isEditMode"
                  :style="{color:'white',fontWeight:'bolder',fontSize:'15px'}"
                  :color="randomTagColor[_.random(0,randomTagColor.length-1)]"
                  v-for="tag in row.resourceTag.split(',')">{{ tag }}
          </el-tag>
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="resourceElement"
                     label="元素">
      <template v-slot="{ row }">
        <div v-if="row.resourceElement===null||row.resourceElement.split(',').length===1">
          暂无数据
        </div>
        <div v-else
             id="element-container">
          <el-tag type="success"
                  :closable="isEditMode"
                  :style="{color:'white',fontWeight:'bolder',fontSize:'15px'}"
                  :color="randomTagColor[_.random(0,randomTagColor.length-1)]"
                  v-for="element in row.resourceElement.split(',')">{{ element }}
          </el-tag>
        </div>
      </template>
    </el-table-column>

    <!-- <el-table-column prop="resourceKey"
                      label="hash"></el-table-column>-->
    <el-table-column prop="resourceValue"
                     width="100"
                     label="文件">
      <template #default="{ row, $index }">
        <el-image
            style="width: 60px; height: 60px"
            :src="row.resourceValue"
            @click="handlePreview($index)"
            fit="fill"
        />
      </template>
    </el-table-column>
    <el-table-column label="Operations"
                     width="220">
      <template #default="{ row }">
        <div class="func-group">
          <el-button type="primary"
                     @click="openDialogAndGetTag(row.resourceValue,row.id)"
                     size="small"
          >获取标签
          </el-button>

          <el-popconfirm
              width="220"
              confirm-button-text="删除"
              cancel-button-text="取消"
              :icon="InfoFilled"
              @confirm="handleDelete(row.id)"
              icon-color="#626AEF"
              title="确定删除该数据吗?该操作会永久删除文件"
          >
            <template #reference>
              <el-button type="danger"
                         size="small"
              >删除
              </el-button>


            </template>
          </el-popconfirm>

        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped
       lang="scss">

.header{
  display: flex;
  //align-items: center;
  gap: 20px;
  height: 50px;
  width: 200px;
  .upload{
    width: 100%;
    height: 100%;
  }
}
.dialog {
  .dialog-header {
    display: flex;
    align-items: center;
    gap: 10px;
  }


  .tag-list {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
    flex-wrap: wrap;
    max-width: 100%;

  }
}

.func-group {
  display: flex;
}

.el-tag {

  ::v-deep .el-tag__close {

    svg {
      path {
        fill: white;
      }
    }
  }
}
#tag-container {
  //display: flex;
  //gap: 6px;
  //overflow-x: auto;
  //overflow-y: hidden;
  //white-space: nowrap;
  //padding-bottom: 10px;
  //user-select: none;

  .el-tag {

    ::v-deep .el-tag__close {

      svg {
        path {
          fill: white;
        }
      }
    }
  }

  &::-webkit-scrollbar {
    height: 10px;
  }

  // 滚动条轨道
  &::-webkit-scrollbar-track {
    height: 10px;
    background: rgb(239, 239, 239);
    border-radius: 2px;
  }

  // 小滑块
  &::-webkit-scrollbar-thumb {
    background: #40a0ff49;
    border-radius: 10px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #40a0ff;
  }
}
</style>
